package com.waves.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.UploadFileRequest;
import com.waves.oss.service.OssService;
import com.waves.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * Created by dlw
 */
@Service
public class OssServiceImpl implements OssService {

    // 上传头像到oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // 从工具类中获取对象
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            // 完善1、 --> 在文件名中添加唯一值
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String filename = uuid + originalFilename;
            // 完善2、 --> 把文件按照日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            // 拼接时间 yyyy/MM/dd/filename
            filename = datePath + "/" + filename;
            // 分片上传初始化
            UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, filename);
            // 将 MultipartFile 转为临时文件
            File tempFile = File.createTempFile("temp", null);
            file.transferTo(tempFile);
            // 设置分片上传参数
            uploadFileRequest.setUploadFile(tempFile.getAbsolutePath()); // 文件路径
            uploadFileRequest.setTaskNum(5); // 并发线程数
            uploadFileRequest.setPartSize(1024 * 1024 * 1); // 每个分片大小 1 MB
            uploadFileRequest.setEnableCheckpoint(true); // 开启断点续传

            // 执行分片上传
            try {
                ossClient.uploadFile(uploadFileRequest);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }

            // 拼接文件访问 URL
            String url = String.format("https://%s.%s/%s", bucketName, endpoint, filename);
            // 删除临时文件
            tempFile.delete();
            // 关闭oss
            ossClient.shutdown();
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}